package so.shanku.essential.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.*;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonParseHelper;
import so.shanku.essential.R;
import so.shanku.essential.activity.ArticalDetailActivity;
import so.shanku.essential.activity.ArticalSearchActivity;
import so.shanku.essential.adapter.ArticalAdapter;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.ExtraKeys;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Jaelyn on 2015/9/6 0006.
 * 页面需要获取屏幕的宽高
 */
public class ArticalFragment extends BaseFragment {

    @ViewInject(R.id.ptr_list)
    private PullToRefreshListView ptr_list;

    private String categoryId;
    /**
     * 信息数据
     */
    private ArrayList<JsonMap<String, Object>> dataList = new ArrayList<JsonMap<String, Object>>();
    private ArticalAdapter articalAdapter;

    /**
     * 搜索
     */
    @ViewInject(R.id.search_ed)
    private EditText search_ed;
    @ViewInject(R.id.do_search_iv)
    private ImageView do_search_iv;
    @ViewInject(R.id.clear_search_iv)
    private ImageView clear_search_iv;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.artical_layout, container, false);
        ViewUtils.inject(this, view);
        LinearLayout searchLayout= (LinearLayout) inflater.inflate(R.layout.search_white_layout,null);
        searchLayout.setVisibility(View.VISIBLE);
        ptr_list.getRefreshableView().addHeaderView(searchLayout);
        ViewUtils.inject(this,searchLayout);
        search_ed.setHint(R.string.theme_search_hint);
        Bundle bundle = getArguments();
        categoryId = bundle.getString(Constant.ID);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        articalAdapter = new ArticalAdapter(activity);
        ptr_list.setAdapter(articalAdapter);
        ptr_list.setMode(PullToRefreshBase.Mode.BOTH);
        ptr_list.setOnRefreshListener(loadMoreListener);
        ptr_list.setOnItemClickListener(onItemClickListener);

        search_ed.setOnEditorActionListener(editorActionListener);
        //ptr_list.scrollBy(0,getResources().getDimensionPixelSize(R.dimen.titlebar_height_sub));
        loadingToast.show();
        getServerData(0);

    }

    /**
     * item  点击监听
     */
    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int itemPosition, long id) {
            if (itemPosition > 1) {
                JsonMap jsonMap_temp = (JsonMap) dataList.get(itemPosition - 2);
                String discoreId = jsonMap_temp.getStringNoNull("articalId");
                Intent intent = new Intent(activity, ArticalDetailActivity.class);
                intent.putExtra(Constant.ID, discoreId);
                intent.putExtra(Constant.NAME, jsonMap_temp.getStringNoNull("articalTitle"));
                activity.jumpTo(intent, false);
            }
           // activity.seeShopDetail("189");
        }
    };

    private PullToRefreshBase.OnRefreshListener2 loadMoreListener = new PullToRefreshBase.OnRefreshListener2() {
        @Override
        public void onPullDownToRefresh(PullToRefreshBase refreshView) {
            getServerData(1);
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase refreshView) {
            getServerData(2);
        }
    };

    /**
     * 获取服务器端数据
     * { "categoryId":0,"time": "","requestType":0}
     * @param requestType 请求类型
     */
    public void getServerData(int requestType) {
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("categoryId", categoryId);
        if(dataList.size()==0){
            requestType=0;
        }
        if(requestType==0) {
            params.put("time", "");
        } else if (requestType == 1) {
            params.put("time",dataList.get(0).getStringNoNull("createTime"));
        }else {
            params.put("time",dataList.get(dataList.size()-1).getStringNoNull("createTime"));
        }
        params.put("requestType",requestType);
        GetDataQueue queue = new GetDataQueue();
        queue.setTag(requestType);

        queue.setActionName(GetDataConfing.Action_GetArticals);
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_GetArticals);
        getDataUtil.getData(queue);
    }


    private TextView.OnEditorActionListener editorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String key = search_ed.getText().toString();
                if (TextUtils.isEmpty(key)) {
                    toast.showToast(R.string.search_key_null);
                    return true;
                } else {
                    Intent intent=new Intent(activity, ArticalSearchActivity.class);
                    intent.putExtra(ExtraKeys.Key_Msg1,key);
                    activity.jumpTo(intent);
                    return true;
                }
            }
            return false;
        }
    };

    @OnClick(R.id.clear_search_iv)
    public void clear_search_iv_click(View view) {
        search_ed.setText("");
    }

    /**
     * 搜索
     *
     * @param view
     */
    @OnClick(R.id.do_search_iv)
    public void do_search_iv_click(View view) {
        String key = search_ed.getText().toString();
        if (TextUtils.isEmpty(key)) {
            toast.showToast(R.string.search_key_null);
        } else {
            Intent intent=new Intent(activity, ArticalSearchActivity.class);
            intent.putExtra(ExtraKeys.Key_Msg1,key);
            activity.jumpTo(intent);
        }
    }

    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {
        @Override
        public void onLoaded(GetDataQueue entity) {
            ptr_list.onRefreshComplete();
            if (entity.isOk()) {
                if (ShowGetDataError.isCodeSuccess(activity, entity.getInfo())) {
                    if (entity.getWhat() == GetDataConfing.What_GetArticals) {
                        ArrayList<JsonMap<String, Object>> temp_data = (ArrayList<JsonMap<String, Object>>) JsonParseHelper.getJsonMap_List_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        setAdapterData(temp_data, (Integer) entity.getTag());
                        validateData();
                    }
                }
            } else {
                ShowGetDataError.showNetError(activity);
            }
            loadingToast.dismiss();
        }

    };

    /**
     * 校验数据 显示无数据等
     * 是否请求正常 网络错误且数据为空的话显示网络异常界面 提供刷新的接口
     *
     * @param
     */
    private void validateData() {
//        if (dataList == null || dataList.size() == 0) {
//            ptr_list.setVisibility(View.GONE);
//            nodataLayout.setVisibility(View.VISIBLE);
//        } else {
//            ptr_list.setVisibility(View.VISIBLE);
//            nodataLayout.setVisibility(View.GONE);
//        }
    }

    private void setAdapterData(ArrayList<JsonMap<String, Object>> temp_data, int requestType) {
        if (requestType == 0){
            if (temp_data.size() == 0) {
                ptr_list.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
            } else {
                ptr_list.setMode(PullToRefreshBase.Mode.BOTH);
                dataList.addAll(0, temp_data);
                articalAdapter.setDatas(dataList);
                articalAdapter.notifyDataSetChanged();
            }

        } else if (requestType == 1) {
            if (!temp_data.isEmpty()) {
                dataList.addAll(0, temp_data);
                articalAdapter.setDatas(dataList);
                articalAdapter.notifyDataSetChanged();
            }
        } else {
            if (temp_data.size() == 0) {
                ptr_list.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
            } else {
                ptr_list.setMode(PullToRefreshBase.Mode.BOTH);
                dataList.addAll(temp_data);
                articalAdapter.setDatas(dataList);
                articalAdapter.notifyDataSetChanged();
            }
        }
    }


}